#coding:utf-8
import functools
from django.shortcuts import render_to_response
from django.http import HttpResponse 
from testlogin.models import MyUser
from django.contrib.auth import authenticate, login
from django.contrib.auth import logout

def create_user(name, key):
    from django.contrib.auth.models import User
    user = User.objects.create_user(username=name, email="", password=key)
    profile = user.get_profile()
    profile.msn = "msn"
    profile.save()
    user.save()

def set_password(name, newkey):
    from django.contrib.auth.models import User
    user = User.objects.get(username__exact=name)
    user.set_password(newkey)
    user.save()

def login_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        login(request, user)
        print "用户名、密码正确！"
        # 转到成功页面
    else:
        print "用户名、密码错误！"
        # 返回错误信息

def logout_view(request):
    logout(request)
    # Redirect to a success page.

def permission_required(fn):
    @functools.wraps(fn)
    def new_view(request,*args,**kwargs):
        if request.user.is_authenticated(): 
            return fn(request,*args,**kwargs)
        else:
            return HttpResponseRedirect('/login/?next=%s' % request.path)
    return new_view
